import java.io.*;
import java.util.*;
import javax.swing.*;

public class SessionManager {

	private static SessionManager instance = null;

	public static SessionManager getInstance() {
		if (instance == null) {
			instance = new SessionManager();
		}

		return instance;
	}

	private HashMap<String, User> users;
	private ArrayList<Session> sessions;

	protected SessionManager() {

		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users.dat"));
			users = (HashMap<String, User>)ois.readObject();
			ois.close();
		}catch(Exception e) {
			// didn't work
			System.out.println("Hello?");
		}

		sessions = new ArrayList<Session>();
	}

	public String login(String username, String password, String position) {
		String message; // to tell the login page what to do

		// get the user who matches the given username
		User currentUser = users.get(username);

		// check if user exists
		if (currentUser == null)
			return "Invalid username.";

		if (!password.equals(currentUser.getPassword()))
			return "Invalid password.";

		// check to see that this user is allowed to take the position
		if (!currentUser.hasPosition(position))
			return "You are unauthorized for this position.";

		// user is authenticated, create a session for the user
		Session session = new Session(currentUser, position);
		sessions.add(session);

		// launch tower control with designated position
		TowerControlFrame towerControl = new TowerControlFrame(session);
		towerControl.setVisible(true);

		return "Success";
	}

	public void logout(Session session) {
		// delete session
		sessions.remove(session);

		// start the login page
		LoginFrame loginFrame = new LoginFrame();
		loginFrame.setVisible(true);
	}

	public void exit() {
		// place holder
	}

	public void saveUser(User user) {
		if (users == null) {
			users = new HashMap<String,User>();
		}
		if (users.containsKey(user.getUsername())) {

			JOptionPane.showMessageDialog(null,"User already exists!");
			return;
		}

		users.put(user.getUsername(), user);
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users.dat"));
			oos.writeObject(users);
			oos.close();
		} catch (Exception e) {
			// didn't work
		}
	}

    public void deleteUser(User user) {
    	if ("admin".equals(user.getUsername())) {
			JOptionPane.showMessageDialog(null,"\"Son of a bitch!\" - Anonymous");
			return;
    	}

    	users.remove(user.getUsername());
    	try {
    		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users.dat"));
    		oos.writeObject(users);
    		oos.close();
    	}catch (Exception e) {

    	}
    }

    public Object[] getUsersArray() {
    	return (users.values().toArray());
    }
}
